'use client';
import React, { useRef, useEffect, useState } from 'react';
import Peer from 'peerjs';
import styles from './page.module.css';
const img1 = '/avatars/1.jpg';
const img2 = '/avatars/2.jpg';
import { FaWifi, FaMobile, FaDesktop, FaSignal } from 'react-icons/fa';

// Define TypeScript interfaces
interface Danmaku {
  id: number;
  text: string;
  top: number;
}

interface Gift {
  id: number;
  name: string;
  price: number;
  icon: string;
}

interface BroadcasterInfo {
  deviceType: string;
  networkStatus: string;
  streamQuality: string;
}

interface GiftAnimation {
  id?: number;
  name?: string;
  icon?: string;
  price?: number;
}

type DeviceType = 'mobile' | 'desktop';
type NetworkStatus = 'excellent' | 'good' | 'poor';
type StreamQuality = '标清' | '高清' | '超清';

const LiveView = () => {  
  // State with TypeScript types
  const [viewerCount, setViewerCount] = useState<number>(0);
  const videoRef = useRef<HTMLVideoElement>(null);
  const [peerId, setPeerId] = useState<string>('');
  const peerRef = useRef<Peer | null>(null);
  const [danmakuList, setDanmakuList] = useState<Danmaku[]>([]);
  const [showGiftList, setShowGiftList] = useState<boolean>(false);
  const [giftAnimation, setGiftAnimation] = useState<GiftAnimation | null>(null);
  const [inputMessage, setInputMessage] = useState<string>('');
  const danmakuRef = useRef<HTMLDivElement>(null);
  const [deviceType, setDeviceType] = useState<DeviceType>('desktop');
  const [networkStatus, setNetworkStatus] = useState<NetworkStatus>('good');
  const [broadcasterInfo, setBroadcasterInfo] = useState<BroadcasterInfo | null>(null);
  const [streamQuality, setStreamQuality] = useState<StreamQuality>('高清');
  const [isConnected, setIsConnected] = useState<boolean>(false);
  const streamBufferRef = useRef<MediaStream | null>(null);

  // Gift list with type
  const gifts: Gift[] = [
    { id: 1, name: '鲜花', price: 1, icon: '🌹' },
    { id: 2, name: '火箭', price: 100, icon: '🚀' },
    { id: 3, name: '钻石', price: 500, icon: '💎' },
    { id: 4, name: '皇冠', price: 1000, icon: '👑' },
  ];

  // Device type detection
  useEffect(() => {
    const checkDeviceType = () => {
      const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
      setDeviceType(isMobile ? 'mobile' : 'desktop');
    };
    
    checkDeviceType();
    
    const handleResize = () => {
      checkDeviceType();
    };
    
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  
  // Network status monitoring
  useEffect(() => {
    const checkNetworkStatus = () => {
      if ('connection' in navigator) {
        const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
        
        if (connection) {
          const updateNetworkStatus = () => {
            const effectiveType = connection.effectiveType;
            const downlink = connection.downlink;
            
            if (effectiveType === '4g' && downlink > 5) {
              setNetworkStatus('excellent');
            } else if (effectiveType === '4g' || (effectiveType === '3g' && downlink > 1)) {
              setNetworkStatus('good');
            } else {
              setNetworkStatus('poor');
            }
          };
          
          updateNetworkStatus();
          connection.addEventListener('change', updateNetworkStatus);
          return () => connection.removeEventListener('change', updateNetworkStatus);
        }
      }
      
      const pingTest = setInterval(() => {
        const start = Date.now();
        fetch('https://www.google.com', { mode: 'no-cors' })
          .then(() => {
            const duration = Date.now() - start;
            if (duration < 100) {
              setNetworkStatus('excellent');
            } else if (duration < 300) {
              setNetworkStatus('good');
            } else {
              setNetworkStatus('poor');
            }
          })
          .catch(() => setNetworkStatus('poor'));
      }, 30000);
      
      return () => clearInterval(pingTest);
    };
    
    const cleanup = checkNetworkStatus();
    return cleanup;
  }, []);
  
  // Get broadcaster ID from URL
  const getBroadcasterId = (): string => {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get('id') || 'broadcaster';
  };

  // Main effect hook
  useEffect(() => {
    const broadcasterId = getBroadcasterId();
    console.log('正在连接到主播:', broadcasterId);
    
    const currentHost = window.location.hostname;
    
    const peer = new Peer({  
      host: currentHost,
      port: 9000,   
      path: '/myapp',
      secure: false,
      debug: 3,
      config: {
        iceServers: [
          { urls: 'stun:stun.l.google.com:19302' },
          { urls: 'stun:stun1.l.google.com:19302' },
          { urls: 'stun:stun2.l.google.com:19302' }
        ]
      }
    });
    
    peerRef.current = peer;
    
    peer.on('open', (id) => {
      setPeerId(id);
      setViewerCount(prevCount => prevCount + 1);
      
      const conn = peer.connect(broadcasterId);
      conn.on('open', () => {
        console.log(`已连接到主播: ${broadcasterId}`);
        setIsConnected(true);
        
        conn.send({
          type: 'viewer_info',
          deviceType: deviceType,
          networkStatus: networkStatus,
          peerId: id
        });
      });
      
      conn.on('error', (err) => {
        console.error('连接错误:', err);
        setIsConnected(false);
      });
      
      conn.on('close', () => {
        console.log('与主播的连接已关闭');
        setIsConnected(false);
      });
    });

    peer.on('call', (call) => {
      call.answer();
      call.on('stream', (remoteStream) => {
        const randomDelay = Math.floor(Math.random() * 6) + 5;
        console.log(`接收到媒体流，将在随机延迟 ${randomDelay} 秒后播放`);
        
        streamBufferRef.current = remoteStream;
        
        if (videoRef.current && videoRef.current.dataset.delayTimerId) {
          const oldTimerId = parseInt(videoRef.current.dataset.delayTimerId);
          console.log(`清除旧的延迟定时器: ${oldTimerId}`);
          clearTimeout(oldTimerId);
          delete videoRef.current.dataset.delayTimerId;
        }
        
        if (videoRef.current && videoRef.current.srcObject) {
          console.log('暂停当前播放以应用新的媒体流');
          videoRef.current.pause();
          videoRef.current.srcObject = null;
        }
        
        const timerId = setTimeout(() => {
          console.log(`随机延迟 ${randomDelay} 秒后开始播放视频`);
          if (videoRef.current && streamBufferRef.current) {
            videoRef.current.srcObject = streamBufferRef.current;
            videoRef.current.play()
              .then(() => console.log('视频开始播放'))
              .catch(e => console.error('播放错误:', e));
          } else {
            console.error('播放失败: 视频元素或媒体流不可用');
          }
        }, randomDelay * 1000);
        
        if (videoRef.current) {
          videoRef.current.dataset.delayTimerId = timerId.toString();
          console.log(`设置新的延迟定时器ID: ${timerId}`);
        }
      });

      call.peerConnection.onicecandidate = (event) => {
        if (event.candidate) {
          const connections = peerRef.current?.connections?.['broadcaster'];
          if (connections) {
            connections.forEach((conn: any) => {
              conn.send({
                type: 'ice_candidate',
                candidate: event.candidate
              });
            });
          }
        }
      };
    });

    peer.on('connection', (conn) => {
      conn.on('data', (data: any) => {
        if (data.type === 'gift') {
          setGiftAnimation(data.gift);
          setTimeout(() => setGiftAnimation(null), 3000);
        } else if (data.type === 'broadcaster_info') {
          setBroadcasterInfo(data);
          setStreamQuality(data.streamQuality);
        } else if (data.type === 'quality_change') {
          setStreamQuality(data.quality);
        } else if (data.type === 'error') {
          console.error('主播端错误:', data.message);
        }
      });
    });

    return () => {
      if (peerRef.current) {
        peerRef.current.destroy();
      }
    };
  }, [deviceType, networkStatus]);

  const connectToBroadcaster = () => {
    if (!peerRef.current || !peerId) return;
    
    const conn = peerRef.current.connect('broadcaster');
    conn.on('open', () => {
      console.log('已连接到主播');
      setViewerCount(prevCount => prevCount + 1);
      setIsConnected(true);
      
      conn.send({
        type: 'viewer_info',
        deviceType: deviceType,
        networkStatus: networkStatus,
        peerId: peerId
      });
    });
    
    conn.on('error', (err) => {
      console.error('连接错误:', err);
      setIsConnected(false);
    });
    
    conn.on('close', () => {
      console.log('与主播的连接已关闭');
      setIsConnected(false);
    });
  };

  const sendDanmaku = () => {
    if (!inputMessage.trim()) return;
    
    const newDanmaku: Danmaku = {
      id: Date.now(),
      text: inputMessage,
      top: Math.random() * 70 + 10,
    };
    
    setDanmakuList(prev => [...prev, newDanmaku]);
    setInputMessage('');

    const conn = peerRef.current?.connect('broadcaster');
    if (conn) {
      conn.on('open', () => {
        conn.send({ 
          type: 'danmaku', 
          text: inputMessage 
        });
      });
    }

    setTimeout(() => {
      setDanmakuList(prev => prev.filter(d => d.id !== newDanmaku.id));
    }, 8000);
  };

  const sendGift = (gift: Gift) => {
    setGiftAnimation(gift);
    setShowGiftList(false);
    
    const conn = peerRef.current?.connect('broadcaster');
    if (conn) {
      conn.on('open', () => {
        conn.send({ 
          type: 'gift', 
          gift 
        });
      });
    }

    setTimeout(() => {
      setGiftAnimation(null);
    }, 3000);
  };

  useEffect(() => {
    if (videoRef.current && videoRef.current.srcObject) {
      if (networkStatus === 'poor') {
        videoRef.current.setAttribute('playsinline', 'true');
        videoRef.current.muted = true;
        videoRef.current.play().then(() => {
          if (videoRef.current) {
            videoRef.current.muted = false;
          }
        }).catch(e => console.error('播放错误:', e));
      }
    }
  }, [networkStatus]);
  
  useEffect(() => {
    return () => {
      if (videoRef.current && videoRef.current.dataset.delayTimerId) {
        clearTimeout(parseInt(videoRef.current.dataset.delayTimerId));
      }
    };
  }, []);
  
  return (
    <div className={`${styles.viewerPage} ${deviceType === 'mobile' ? styles.mobilePage : ''}`}>
      <div className={styles.appContainer}>
        <div className={styles.element1}>
          <div>
            <img src={img1} alt="主播头像" />
          </div>
          <div>
            <span>Z</span>
            <p>{viewerCount} 人观看</p>
          </div>
        </div>

        <div className={styles.element2}>
          <button onClick={connectToBroadcaster}>连接主播</button>
        </div>

        <div className={styles.element3}>
          <img src={img2} alt="图标" />
          <span>1</span>
        </div>

        <div className={styles.closeButton}>
          {/* <span onClick={() => navigate('/')}>×</span> */}
        </div>
      </div>

      <div className={styles.broadcasterContainer}>
        <div className={styles.webcamContainer}>
          <video 
            ref={videoRef} 
            controls 
            autoPlay 
            playsInline 
            className={networkStatus === 'poor' ? styles.lowQualityVideo : ''}
          />
          
          <div className={styles.deviceIndicator}>
            {deviceType === 'mobile' ? <FaMobile /> : <FaDesktop />} {deviceType === 'mobile' ? '移动设备' : '桌面设备'}
          </div>
          
          <div className={`${styles.networkIndicator} ${styles[networkStatus]}`}>
            <FaWifi /> {networkStatus === 'excellent' ? '极佳' : networkStatus === 'good' ? '良好' : '一般'}
          </div>
          
          <div className={styles.qualityIndicator}>
            <FaSignal /> {streamQuality}
          </div>
          
          <div className={`${styles.connectionIndicator} ${isConnected ? styles.connected : ''}`}>
            {isConnected ? '已连接' : '未连接'}
          </div>
          
          <div className={styles.danmakuContainer} ref={danmakuRef}>
            {danmakuList.map(danmaku => (
              <div
                key={danmaku.id}
                className={styles.danmaku}
                style={{ top: `${danmaku.top}%` }}
              >
                {danmaku.text}
              </div>
            ))}
          </div>

          {giftAnimation && (
            <div className={styles.giftAnimation}>
              <span>{giftAnimation.icon}</span>
            </div>
          )}

          <div className={styles.overlayText}>
            欢迎来到直播间！
          </div>
          <div className={styles.overlayText1}>
            <span>小董来了</span>
          </div>
          
          <div className={`${styles.controlsContainer} ${deviceType === 'mobile' ? styles.mobileControls : ''}`}>
            <input
              type="text"
              className={styles.messageInput}
              placeholder="发送弹幕..."
              value={inputMessage}
              onChange={(e) => setInputMessage(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && sendDanmaku()}
            />
            <button className={styles.sendButton} onClick={sendDanmaku}>
              发送
            </button>
            <button className={styles.giftButton} onClick={() => setShowGiftList(!showGiftList)}>
              礼物
            </button>
          </div>

          {showGiftList && (
            <div className={styles.giftListContainer}>
              {gifts.map(gift => (
                <div key={gift.id} className={styles.giftItem} onClick={() => sendGift(gift)}>
                  <span className={styles.giftIcon}>{gift.icon}</span>
                  <div className={styles.giftName}>{gift.name}</div>
                  <div className={styles.giftPrice}>{gift.price} 钻石</div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default LiveView;